import re

from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

from home.models import HealthInfoCategory, HealthCategory, SubCategory, HealthItem, Hospital, Department, \
    Doctor, UserQuestion, DoctorResponse, Medicine, DoctorHospitalMedicine, UserModel, Video, Patient


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserModel
        fields = ['id', 'username', 'phone', 'email', 'password', 'avatar', 'nickname']


# token 自定义
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)
        return token


# 用户注册
class UserRegisterSerializer(serializers.ModelSerializer):
    re_password = serializers.CharField(max_length=128, write_only=True)
    code = serializers.CharField(max_length=6, write_only=True)
    access_token = serializers.CharField(max_length=255, read_only=True)
    refresh = serializers.CharField(max_length=255, read_only=True)

    class Meta:
        model = UserModel
        fields = ['username', 'password', 'code', 'email', 'phone', 'access_token', 'refresh', 're_password']

    def validate(self, attrs):
        phone = attrs.get('phone')
        code = attrs.get('code')
        re_password = attrs.get('re_password')
        if not phone or not code or not re_password:
            raise serializers.ValidationError('手机号，验证码，密码不能为空')
        if not re.match('^1[3-9]\d{9}$', phone):
            raise serializers.ValidationError('手机号格式不正确')
        if re_password != attrs.get('password'):
            raise serializers.ValidationError('两次密码不一致')
        redis = get_redis_connection("sms_code")
        sms_code = redis.get(f"sms_code_{phone}")
        if not sms_code:
            raise serializers.ValidationError('验证码已过期')
        if int(code) != int(sms_code.decode()):
            raise serializers.ValidationError('验证码错误')
        redis.delete(f"sms_code_{phone}")
        try:
            UserModel.objects.get(phone=phone)
            raise serializers.ValidationError('手机号已注册')
        except UserModel.DoesNotExist:
            print("手机号未注册,可以注册")

        attrs.pop('re_password')
        attrs.pop('code')
        return attrs

    def create(self, validated_data):
        phone = validated_data.get('phone')
        password = validated_data.get('password')
        user = UserModel.objects.create_user(
            username=phone,
            phone=phone,
            password=password,
        )
        token_ser = MyTokenObtainPairSerializer()
        refresh = token_ser.get_token(user)
        print(refresh, '\n', "refresh")
        user.refresh = str(refresh)
        user.access_token = str(refresh.access_token)
        user.save()
        return user


# 问医生9个分类
class HealthInfoCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = HealthInfoCategory
        fields = "__all__"


# # 大健康和生活手册
class HealthCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = HealthCategory
        fields = "__all__"


#   大健康和生活手册-一级类
class HealthCategorySubSerializer(serializers.ModelSerializer):
    class Meta:
        model = SubCategory
        fields = "__all__"


# 大健康和生活手册-二级类
class HealthItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = HealthItem
        fields = "__all__"


# 医院模型
class HospitalSerializer(serializers.ModelSerializer):
    class Meta:
        model = Hospital
        fields = "__all__"


# 科室模型
class DepartmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Department
        fields = "__all__"


# 医生模型
class DoctorSerializer(serializers.ModelSerializer):
    # 给一个医生模型，返回其所属科室和医院信息
    department = serializers.SerializerMethodField(read_only=True)
    hospital = serializers.SerializerMethodField(read_only=True)

    def get_department(self, obj):
        return obj.primary_department.name

    def get_hospital(self, obj):
        return obj.hospital.name

    class Meta:
        model = Doctor
        fields = "__all__"


# 用户咨询
class UserQuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserQuestion
        fields = "__all__"


# 医生回复
class DoctorResponseSerializer(serializers.ModelSerializer):
    class Meta:
        model = DoctorResponse
        fields = "__all__"


# 药物模型
class MedicineSerializer(serializers.ModelSerializer):
    class Meta:
        model = Medicine
        fields = "__all__"


# 将医生-医院-科室-药品的多对多关系建立起来
class DoctorMedicineSerializer(serializers.ModelSerializer):
    class Meta:
        model = DoctorHospitalMedicine
        fields = "__all__"


class VideoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Video
        fields = "__all__"


class PatientSerializer(serializers.ModelSerializer):
    class Meta:
        model = Patient
        fields = "__all__"
